package com.tz.pay.marlon.core.service;

import java.io.File;
import java.io.IOException;
import java.net.Inet4Address;
import java.net.InetAddress;
import java.net.InterfaceAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.jdom.JDOMException;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.tz.pay.PayBean;
import com.tz.pay.marlon.core.utils.CommonUtilPub;
import com.tz.pay.marlon.core.utils.ConfigUtil;
import com.tz.pay.marlon.core.utils.PayCommonUtil;
import com.tz.pay.marlon.core.utils.QRCodeEncoder;
import com.tz.util.jdomXMLUtil;

public class PaymentAct {
	public static String goWeixinPay(PayBean payBean,HttpServletRequest request,HttpServletResponse response){
		//订单查询
    	String product_id=payBean.getPno();
    	//获得微信二维码地址
		String codeurl= PaymentAct.getcodeUrl(product_id,payBean);
		//获取项目地址
		String path=request.getSession().getServletContext().getRealPath("/");
		//获取图片的地址
    	String picPath = PaymentAct.getQrurl(path,codeurl,product_id);
//    	System.out.println("#############picPath=="+picPath);
    	
    	Map<String, String> map=new HashMap<String, String>();
    	String aaa = PaymentAct.queryOrder(product_id);
    	try {
			map = jdomXMLUtil.doXMLParse(aaa);
		} catch (JDOMException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
    	
    	String returnCode = map.get("return_code");
        String resultCode = map.get("result_code");
        String trade_state_desc = map.get("trade_state_desc");
        String cash_fee = map.get("cash_fee");
        if(returnCode.equalsIgnoreCase("SUCCESS")&&resultCode.equalsIgnoreCase("SUCCESS")){
	        if(cash_fee!=null&&!"".equals(cash_fee))
	        {
	        	System.out.println("cash_fee=="+cash_fee);
	        	double a = Double.parseDouble(cash_fee);
	        	System.out.println("aa=="+a);
	        	double tota = (a / 100);
	        	System.out.println("tota=="+tota);
	        }else if(trade_state_desc!=null&&!"".equals(trade_state_desc)){
	        	System.out.println("trade_state_desc=="+trade_state_desc);
	        }
        }else{
        	System.out.println("支付异常");
        }
//		System.out.println("开始时间"+new Date());
//		try {
//			Thread.sleep(6000);//10秒
//		} catch (Exception e) {
//			System.exit(0);// 退出程序
//		}
//		System.out.println(	"成功了"+ new Date());
		return picPath;
	}
    
    /**
     * 查询订单
     */
    public static String queryOrder(String product_id){
    	String result =CommonUtilPub.httpsRequest(ConfigUtil.CHECK_ORDER_URL, "POST", initXmlDataQuery(product_id));
    	System.out.println(result);
    	return result;
    }
	 /**
     * 下载二维码图片到本地并返回路径字符串
     */
    public static String getQrurl(String path,String wxCodeUrl,String product_id){
    	if(!"fail".equals(wxCodeUrl)){
    		String codeUrl = "";
    		String urls = "";
    		// 图片的实际路径
    		String imgfile ="";
    		// 图片的网路路径
    		String imgurl ="";
    		byte[] imgs = QRCodeEncoder.createQRCode(wxCodeUrl);
			urls = path + "AwinXinPhoto" +java.io.File.separator;
			System.out.println(urls+"--------");
			// 图片的实际路径
			imgfile = urls + product_id + ".png";
//			System.out.println(imgfile);
			// 图片的网路路径
//			imgurl = path+java.io.File.separator + product_id + ".png";
			imgurl = "http://localhost:8080/tzpay/AwinXinPhoto/" + product_id + ".png";
			System.out.println(imgurl);
			File savefile = new File(imgfile);
			if (!savefile.getParentFile().exists())
				savefile.getParentFile().mkdirs();
			QRCodeEncoder.saveImage(imgs, imgfile, "png");
			// System.out.println(imgs);
			JSONArray jsons = new JSONArray();
			// json
			JSONObject json = new JSONObject();
			json.put("product_id", product_id);
			json.put("imgurl", imgurl);
			json.put("codeUrl", codeUrl);
			jsons.add(json);
			JSONObject jsondata = new JSONObject();
			jsondata.put("data", jsons);
//			System.out.println("imgfile=="+imgfile);
//			System.out.println("imgurl=="+imgurl);
			return imgurl;
    	}
    	return null;
    }
    /**
     * 得到微信返回的codeurl
     * 
     * 
     */
    public static String getcodeUrl(String product_id,PayBean payBean){
    	String result =CommonUtilPub.httpsRequest(ConfigUtil.UNIFIED_ORDER_URL, "POST", initXmlData(product_id,payBean));
//        System.out.println("result=="+result);
        Map<String, String> map=new HashMap<String, String>();
		try {
			map = jdomXMLUtil.doXMLParse(result);
		} catch (JDOMException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
        String returnCode = map.get("return_code");
        String resultCode = map.get("result_code");
        if(returnCode.equalsIgnoreCase("SUCCESS")&&resultCode.equalsIgnoreCase("SUCCESS")){
           String codeUrl = map.get("code_url");
           //TODO 拿到codeUrl，写代码生成二维码
//           System.out.println("codeUrl="+codeUrl);
           return codeUrl;
        }else{
        	return "fail";
        }
    }
    
    /**
     * 查询订单初始化数据
     * 
     * 
     */
    public static String initXmlDataQuery(String product_id){
    	HashMap<String, String> paramMap = new HashMap<String, String>();
    	paramMap.put("appid", ConfigUtil.APPID); //appid
    	paramMap.put("mch_id", ConfigUtil.MCH_ID); //商户号
    	paramMap.put("out_trade_no", product_id); //商户 后台的贸易单号
    	paramMap.put("nonce_str", PayCommonUtil.CreateNoncestr());  //随机数
    	
    	paramMap.put("sign", PayCommonUtil.createSign3("UTF-8", paramMap,ConfigUtil.API_KEY));//根据微信签名规则，生成签名
    	
    	String xmlData = CommonUtilPub.mapToXml(paramMap);//把参数转换成XML数据格式
    	System.out.println("xmlData=="+xmlData);
        return xmlData;
    }
    
    /**
     * 初始化数据 返回xml字符串
     */
    public static String initXmlData(String product_id,PayBean payBean){
    	HashMap<String, String> paramMap = new HashMap<String, String>();
    	paramMap.put("trade_type", "NATIVE"); //交易类型
    	paramMap.put("spbill_create_ip",localIp()); //本机的Ip
    	paramMap.put("product_id", product_id); // 商户根据自己业务传递的参数 必填
    	paramMap.put("body", payBean.getDesc());         //描述
    	paramMap.put("out_trade_no", product_id); //商户 后台的贸易单号
    	paramMap.put("total_fee", String.valueOf(1000)); //金额必须为整数  单位为分
    	paramMap.put("notify_url", "http://" + getAccessDomain() + "/tzpay/weixin/checkpay.html"); //支付成功后，回调地址
    	paramMap.put("appid", ConfigUtil.APPID); //appid
    	paramMap.put("mch_id", ConfigUtil.MCH_ID); //商户号
    	paramMap.put("nonce_str",  PayCommonUtil.CreateNoncestr());  //随机数  "SzLDWOln7FOrjlll"
    	paramMap.put("sign", PayCommonUtil.createSign2("UTF-8", paramMap,ConfigUtil.API_KEY));//根据微信签名规则，生成签名
    	
    	String xmlData = CommonUtilPub.mapToXml(paramMap);//把参数转换成XML数据格式
//    	System.out.println(xmlData);
    	return xmlData;
    }
    
	private static String localIp(){
		String ip = null;
		Enumeration allNetInterfaces;
				try {
					allNetInterfaces = NetworkInterface.getNetworkInterfaces();            
					while (allNetInterfaces.hasMoreElements()) {
						NetworkInterface netInterface = (NetworkInterface) allNetInterfaces.nextElement();
						List<InterfaceAddress> InterfaceAddress = netInterface.getInterfaceAddresses();
						for (InterfaceAddress add : InterfaceAddress) {
							InetAddress Ip = add.getAddress();
							if (Ip != null && Ip instanceof Inet4Address) {
								ip = Ip.getHostAddress();
							}
						}
					}
				} catch (SocketException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			return ip;
		}
	
    private static String getAccessDomain(){
    	return "10.72.236.112:8080";
    }
}
